# Create your views here.
#conttrib.localflavors
#from django.shortcuts import HttpResponse
from django.forms import  ModelForm
from iFriends.People.models import Person
from iFriends.People.models import Blog
from django.shortcuts import render_to_response, get_object_or_404
from iFriends.Quotes.models import Quote
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
import datetime
from django.http import HttpResponseRedirect ,HttpResponse


def index(request):
    pList = Person.objects.all()
    return render_to_response('people/person_index.html' , {'pList' : pList})

#def details(request):
#   html = "<HTML><BODY><H1>Person Details Index</H1><HR></BODY></HTML>"
#    return HttpResponse(html)
@login_required
def details(request , pID='0' , opts = ()):
    rDict = {}
    p = get_object_or_404(Person, pk=pID)
    rDict['p'] = p
    quotes = Quote.objects.all()
    rDict['quotes'] = quotes
#Linhas adicionadas
    pageLinks = {'name': 'People', 'value' : '/People/'}
    rDict['pageLinks'] = pageLinks
    return render_to_response('People/person_details.html' , rDict,context_instance = RequestContext(request))


def detailsnome(request , name=""):
    response = HttpResponse()
    response.write("<HTML><BODY>\n")
    if( name == ""):
        response.write("<H1>Person Details Index</H1><HR>\n")
    else:
        response.write("<H1>Details for Person %s</H1><HR>\n" % name)
        response.write("(details go here)")
    response.write("</BODY></HTML>")
    return response

def index_blog(request):
    response = HttpResponse()
    response.write("<html><body>\n")
    response.write("<h1>Blog</h1><hr>")
    bList = Blog.objects.all()
    for b in bList:
        link = "<a href=\"Info/%s\">" % (b.title)
        response.write("<li>%s%s</a></li>" % (link, b.text))
    response.write("</body></html>")
    return response  

def details_blog(request , name = ''):
    response = HttpResponse()
    response.write("<HTML><BODY>\n")
    try:
        b = Blog.objects.get(title=name)
        response.write("<h1>Details for Person %s</h1><hr>\n" % b.title)
        response.write("<li>Text : %s</li>" % b.text)
    except Blog.DoesNotExist:
        response.write("Blog Not Found")
    response.write("</BODY></HTML>")
    return response

class PersonForm(ModelForm):
    class Meta:
        model = Person


def person_form(request, pID='0'):
    pForm = PersonForm()
    p = get_object_or_404(Person, pk=pID)
    message = 'Unknown Request'
    
    if request.method == 'GET':
        pForm = PersonForm(instance=p)
        message ='Editing person %s' % p.name
    if request.method == 'POST':
        if request.POST['submit'] == 'update':
            message = 'Update Request for %s.' % p.name
            pForm = PersonForm(request.POST.copy(), instance=p)
            if pForm.is_valid():
#                message += ' Valid.'
                try:
                    pForm.save()
                    message += ' Updated'
                except:
                    message += ' Database Error.'
            else:
                message += ' Invalid.'
    return render_to_response('People/person_form.html',{'pForm':pForm, 'message':message})




class BlogForm(ModelForm):
    class Meta:
        model=Blog
       
        
#def blog_form(request, pID='0'):
def add_blog(request, pID='0'):
    if not request.user.has_perm('People.can_blog'):
        return HttpResponseRedirect('/')
    
    p = get_object_or_404(Person, userID=request.user)
    bf = BlogForm()
    message = 'Unknown Request'
    
    if request.method == 'GET':
        message = 'Add Blog for %s' % p.name
    if request.method == 'POST':
        if request.POST['submit'] == 'Add':
            bf = BlogForm(request.POST.copy())
#            bf.__setattr__('date', datetime.datetime )
            if bf.is_valid():
                try:
                    bObj = bf.save()
                    p.blogs.add(bObj)
                    p.save()
                    message = 'Blog added to %s.' % p.name
                except:
                    message = 'Database Error.'
            else:
                message = 'Invalid data in Form.'

    return render_to_response(
        'Blogs/add_blog_form.html',
         {'bForm':bf, 'message': message})

def update_blog(request, bID='0'):
    blog = get_object_or_404(Blog, pk=bID)
    bf =  BlogForm(instance=blog)
    message = 'Update Blog'
    
    if request.method == 'POST':
        if request.POST['submit'] == 'Update':
            blog.title = request.POST['title']
            blog.text = request.POST['text']
            blog.date = datetime


